import java.util.ArrayList;

/*
 * @lc app=leetcode.cn id=6 lang=java
 *
 * [6] Z 字形变换
 */

// @lc code=start
class Solution {

    /**
     * Accepted
    1157/1157 cases passed (4 ms)
    Your runtime beats 86.64 % of java submissions
    Your memory usage beats 76.53 % of java submissions (41.8 MB)
     */
    public String convert(String s, int numRows) {
        int len = s.length();
        if (numRows == 1 || numRows >= len) {
            return s;
        }
        StringBuilder[] builders = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++) {
            builders[i] = new StringBuilder();
        }
        int step = 1, j = 0;
        for (int i = 0; i < len; i++) {
            builders[j].append(s.charAt(i));
            j = j + step;
            if (j == numRows - 1) {
                step = -1;
            }
            if (j == 0) {
                step = 1;
            }
        }
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            result.append(builders[i]);
        }
        return result.toString().trim();
    }
}
// @lc code=end
